package com.scalar.chiptrack.adaptor.utac;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * User: ChandraSekhar
 * Date: Jan 17, 2008
 * Time: 2:11:21 PM
 */
public class UTACFTPAdaptor extends JobHandler implements AdaptorConstants
{

    private static final int    PORT            = 21;
    private static final String FTP_HOST        = "usg1-ftp.sg.utacgroup.com";
    public  static final String ADAPTOR_NAME    = "UTAC_SORT_BIN";
    public static final String FILE_NAME_SORT_WIP = "utac_sort_bin";
    private static final String FILE_EXTN       = ".TXT";
    private String m_sortdir                    = "/From_UTAC/production/";

    private String m_username           = null;
    private String m_password           = null;
    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private int    m_adaptor_id         = -1;
    private String fileDate             = null;

    

    public UTACFTPAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_UTAC_SING, WIP_TYPE_SORT );

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger(m_dataOutputDir, VENDOR_NAME_UTAC_SING);
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading UTAC SING FTP Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new UTACFTPAdaptor().execute();
    }

    public void execute() throws Exception
    {
        java.util.Date begDate = null;
        try
        {
            //Getting the last Run Adaptor file Date ( As we are Inserting in the new Adaptor run info in the Starting itself)
            fileDate   = AdaptorRunInfo.getAdaptorLastParsedFileDate( ADAPTOR_NAME );

            //When File Date is NULL Setting the File Date Back to 4 Days From Current Date
            if ( fileDate == null )
            {
            	Calendar cal = Calendar.getInstance();
                cal.add( Calendar.DAY_OF_MONTH, -4 );
                begDate = cal.getTime();
                fileDate = StringUtils.formatDateToString( begDate, "MM/dd/yyyy");
            }

            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader("UTAC SING SORT FTP", CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
            log( "Successfully logged in to " + FTP_HOST );
            System.out.println( "Successfully logged in to " + FTP_HOST );

            // change the directory to data
            ftp.chdir( "/" + m_username + m_sortdir);
            log("Remote directory changed to " + m_sortdir);
            System.out.println("Remote directory changed to " + m_sortdir);

            //To Down DownLoad the File To Local System at Specepied path
            downloadSortWIPFiles( ftp );

            // Log out
            logout( ftp );
            log( "\nSuccessfully logged out from UTAC SING Ftp Site" );
            System.out.println( "\nSuccessfully logged out from UTAC SING FTP Site" );
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    /**
     *
     * @param host
     * @param port
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    private FTPClient login( String host, int port, String username, String password ) throws Exception
    {
        FTPClient ftp = new FTPClient( host, port );
        ftp.login( username, password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

   private void downloadSortWIPFiles( FTPClient ftp ) throws Exception
   	{

   		String[] directoryListing = ftp.dir( "", true );

        if ( ( directoryListing == null ) || ( directoryListing.length == 0 ) )
        {
            return;
        }

        byte[] buf = null;

        FileOutputStream fileOutputStream = null;

        try
        {
            java.util.Date maxDate  = null;
            java.util.Date tempmaxDate  = null;
            String tempFileName     = null;

            System.out.println("\tDownloading Sort Bin files....");
            String directoryName = null;

            /* To get the latest maxdate */
            for ( int i = 0; i < directoryListing.length; i++ )
            {
                directoryName = directoryListing[i].substring( directoryListing[i].lastIndexOf( ' ' ) ).trim();
                
                if(  directoryName != null && !directoryName.equalsIgnoreCase( "." ) && !directoryName.equalsIgnoreCase( "FT" ) && !directoryName.equalsIgnoreCase( ".." ) )
            	{                       
        			if( "d".equalsIgnoreCase( directoryListing[i].substring( 0, 1 ) ) )
        			{
        				fileDate = fileDate.replaceAll("/","");

                        java.util.Date date1 = StringUtils.format( fileDate, "MMddyyyy" );
						java.util.Date date2 = getDateFromString( directoryListing[i] );

						if ( date2.compareTo( date1 ) >= 0 )
        				{
                            /* This code to get the Max date and inserting in to DB*/
                            /*Started Here*/
                            maxDate = date2;
                            if ( tempmaxDate == null )
                            {
                                tempmaxDate = maxDate;
                            }
                            else
                            {
                                if ( maxDate.compareTo( tempmaxDate ) > 0 )
                                {
                                    tempmaxDate = maxDate;
                                }
                            }
                            /*Ended here */
        					log( "Changing to.. " + directoryName );
            				ftp.chdir( directoryName + "/" );
            				String[] fileListings = ftp.dir();
            				for ( int k = 0; k < fileListings.length; k++ )
                            {
                                if ( ( fileListings[k].endsWith( ".lotsum" )  ) )
                                {
                                    tempFileName = fileListings[k];
                                    if ( fileDate != null && tempFileName != null )
                                    {
                                        log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                                        if ( m_adaptor_id > 0 )
                                        {
                                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_TXT, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                                        }
                                        buf = ftp.get( tempFileName );
                                        tempFileName = FILE_NAME_SORT_WIP + "_" + tempFileName + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;
                                        fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                                        fileOutputStream.write( buf );
                                        fileOutputStream.flush();
                                        tempFileName = null;
                                    }
                                }

                            }
            				ftp.chdir( ".." );
        				}
        				else
        				{
        					log( "The dates do not compare" );
        				}
                    }
            	}
            }
            if ( tempmaxDate != null )
            {
                //To Save the Last Modified date from ftp server
                String maxfileDate = StringUtils.formatDateToString( tempmaxDate,"MM/dd/yyyy");
                log( "maxfileDate = " + maxfileDate );
                AdaptorRunInfo.updateLastRunFileDate( m_adaptor_id , maxfileDate );
            }
        }
        catch ( Exception e )
        {
            log ("Exception while downloading......... " + e);
            logout( ftp );
            throw e;
        }

        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();

                }
                catch ( IOException ignore )
                {
                }
           }
       }
   }


   	private Date getDateFromString( String dirString )
   	{
   		String dateString = null;
        String yearString = null;
        Date dt = null;

   		if( dirString == null || dirString.length() == 0 )
   		{
   			System.out.println( " Dir String is null " );
   			return new Date();
   		}

   		try
		{               
            dateString = dirString.substring( ( dirString.indexOf( "0 ") + 2 ), dirString.indexOf( "0 " )  + 8 );
            dateString = dateString.replaceAll( " ", "" );

            yearString = dirString.substring( ( dirString.indexOf( "0 ") + 8 ), dirString.indexOf( "0 " )  + 14 );
            yearString = yearString.replaceAll( " ", "" );
            
            if ( yearString.indexOf(":") != -1 )
            {   
                Calendar cal = Calendar.getInstance();
                java.util.Date curDate = cal.getTime();

                yearString = StringUtils.formatDateToString( curDate, "yyyy" );
            }

            dt = StringUtils.format( dateString + yearString , "MMMddyyyy" );

        }
   		catch( Exception e )
		{
   			e.printStackTrace();
   			dt = new Date();
		}
		
		return dt;
   	}
    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }
        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From UTAC SING FTP Site" + ignore );
            throw ignore;
        }
        ftp = null;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

